<template>
  <div v-loading="loading">
    <div class="mb-10px mt-10px p-2 text-right bg-white">
      <a-button type="primary" style="margin-right: 10px" @click="handleCreate"> 设置 </a-button>
    </div>
    <BasicTable @register="registerTable">
      <template #toolbar> </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: '删除',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record, 2),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <BasicTable @register="registerTableUser" style="margin-top: 10px">
      <template #toolbar> </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: '删除',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record, 1),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <BasicTable @register="registerTableUserGroup" style="margin-top: 10px">
      <template #toolbar> </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: '删除',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record, 0),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <SelectAll @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { getPrivDetail } from '/@/api/system/system';
  import { useModal } from '/@/components/Modal';
  import { SelectAll } from '/@/components/CustomComp';
  import { columns, columnsUser, columnsUserGroup, searchFormSchema } from './privView.data';
  import { useRouter } from 'vue-router';
  import { useTabs } from '/@/hooks/web/useTabs';
  import {
    getAdminSetRoleGroupUser,
    getAdminDelRolePriv,
    getAdminDelUserPriv,
    getAdminDelGroupPriv,
  } from '/@/api/flowManage/flowManage';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'PrivView',
    components: {
      BasicTable,
      SelectAll,
      TableAction,
    },
    setup() {
      const { currentRoute } = useRouter();
      const { setTitle } = useTabs();
      const listAll = ref<Recordable>({});
      const priv = ref('');
      const loading = ref(false);
      const { createMessage } = useMessage();
      const [registerModal, { openModal }] = useModal();
      const [registerTable, { setTableData: setTableDataRole }] = useTable({
        title: '角色',
        columns,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
        },
        searchInfo: {}, //额外的参数
        tableSetting: {
          redo: false,
        },
        pagination: false,
        useSearchForm: false,
        showTableSetting: true,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: false,
        canResize: false,
        actionColumn: {
          width: 80,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
      });
      const [registerTableUser, { setTableData: setTableDataUser }] = useTable({
        title: '用户',
        columns: columnsUser,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
        },
        searchInfo: {}, //额外的参数
        tableSetting: {
          redo: false,
        },
        pagination: false,
        useSearchForm: false,
        showTableSetting: true,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: false,
        canResize: false,
        actionColumn: {
          width: 80,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
      });
      const [registerTableUserGroup, { setTableData: setTableDataUserGroup }] = useTable({
        title: '用户组',
        columns: columnsUserGroup,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
        },
        searchInfo: {}, //额外的参数
        tableSetting: {
          redo: false,
        },
        pagination: false,
        useSearchForm: false,
        showTableSetting: true,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: false,
        canResize: false,
        immediate: false,
        actionColumn: {
          width: 80,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
      });

      function handleCreate() {
        let hadUsers = [];
        if (listAll.value.allPriv && listAll.value.allPriv.length) {
          hadUsers = listAll.value.allPriv.map((item) => {
            return {
              key: item.code,
              name: item.code,
              title: item.name,
              realName: item.name,
              newTitle: item.name,
              privType: item.kind,
            };
          });
        }
        console.log('hadUsers', hadUsers);
        openModal(true, {
          isUpdate: false,
          tabKeys: ['2', '3', '4'],
          users: hadUsers,
        });
      }

      async function handleDelete(record: Recordable, type) {
        try {
          let api: any = null;
          const params = {
            priv: priv.value,
          };
          if (type == 2) {
            params.roleCode = record.code;
            api = getAdminDelRolePriv;
          } else if (type == 1) {
            params.userName = record.userName;
            api = getAdminDelUserPriv;
          } else if (type == 0) {
            params.groupCode = record.code;
            api = getAdminDelGroupPriv;
          }
          loading.value = true;
          await api(params);
          fetch();
          createMessage.success('操作成功');
        } catch (error) {
        } finally {
          loading.value = false;
        }
      }
      async function handleSuccess(users) {
        try {
          console.log('users', users);
          if (users && users.length > 0) {
            let dataList: Recordable[] = [];
            users.forEach((item) => {
              let name = item.key;
              if (item.privType == 3) {
                name = item.code;
              }
              dataList.push({
                code: name,
                name: item.title,
                kind: item.privType,
              });
            });
            const formData = {
              priv: priv.value,
              roleGroupUser: JSON.stringify(dataList),
            };
            loading.value = true;
            await getAdminSetRoleGroupUser(formData);
            fetch();
            createMessage.success('操作成功');
          }
        } catch (error) {
        } finally {
          loading.value = false;
        }
      }

      const fetch = async () => {
        const { query } = currentRoute.value;
        if (query.title) {
          setTitle('权限查看' + '-' + query.title);
        }
        if (query.priv) {
          priv.value = query.priv;
          const res = await getPrivDetail({ priv: query.priv });
          listAll.value = res;
          const { roleList, groupList, list } = res;
          setTableDataRole(roleList);
          setTableDataUser(list);
          setTableDataUserGroup(groupList);
        }
      };
      onMounted(fetch);

      return {
        registerTable,
        registerModal,
        handleCreate,
        handleDelete,
        handleSuccess,
        registerTableUser,
        registerTableUserGroup,
        loading,
      };
    },
  });
</script>
